package com.example.common.config;

import com.example.common.response.R;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.*;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Collections;
import java.util.List;

@Configuration
@EnableKnife4j
@EnableSwagger2
@EnableOpenApi
public class SwaggerConfig {
    
    //public static final String AUTHORIZATION_HEADER = "Access-Token";
    public static final String AUTHORIZATION_HEADER = "token";
    public static final String DEFAULT_INCLUDE_PATTERN = "/api/.*";
    
    private static final RequestParameter requestParameter = new RequestParameterBuilder()
            .name("token")
            .description("token")
            .in(ParameterType.HEADER)
            .required(false)
            .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
            .build();
    
    @Bean(value = "defaultApi")
    public Docket defaultRestApi() {
        
        return new Docket(DocumentationType.OAS_30)
                .groupName("default")
                .apiInfo(simpleApiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                //.paths(PathSelectors.regex("(?!/error.*).*"))
                .build()
        
                // globalRequestParameters 这个配置可以让所有接口请求时出现一个参数输入框
                .globalRequestParameters(Collections.singletonList(requestParameter))
                .securityContexts(Lists.newArrayList(securityContext()))
                .securitySchemes(Lists.newArrayList(apiKey()))
                
                //下面是swagger访问需要携带的token
                /*.globalRequestParameters(
                        singletonList(new springfox.documentation.builders.RequestParameterBuilder()
                                // 不能叫Authorization
                                .name("token")
                                .description("token")
                                .in(ParameterType.HEADER)
                                .required(false)
                                .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                                .build()))*/
                ;
    }
    
    /**
     * new config
     * @return
     */
    @Bean(value = "workflowApi")
    public Docket workflowApi() {
        return new Docket(DocumentationType.OAS_30)
                .groupName("工作流")
                .apiInfo(simpleApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("xiaofang.hs.workflow")
                        .and(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)))
                .paths(PathSelectors.any())
                .build()
                
                .genericModelSubstitutes(R.class)
        
                .globalRequestParameters(Collections.singletonList(requestParameter))
                .securityContexts(Lists.newArrayList(securityContext()))
                .securitySchemes(Lists.newArrayList(apiKey()));
    }
    
    /**
     * new config
     * @return
     */
    @Bean(value = "sysNoticeApi")
    public Docket sysNoticeApi() {
        return new Docket(DocumentationType.OAS_30)
                .groupName("消息通知")
                .apiInfo(simpleApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("xiaofang.hs.sysNotice")
                        .and(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)))
                .paths(PathSelectors.any())
                .build()
        
                .globalRequestParameters(Collections.singletonList(requestParameter))
                .securityContexts(Lists.newArrayList(securityContext()))
                .securitySchemes(Lists.newArrayList(apiKey()));
    }
    
    @Bean(value = "sysUser")
    public Docket sysUserApi() {
        return new Docket(DocumentationType.OAS_30)
                .groupName("用户管理")
                .apiInfo(simpleApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("xiaofang.hs.systemmanagement")
                        .and(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)))
                .paths(PathSelectors.any())
                .build()
                
                .globalRequestParameters(Collections.singletonList(requestParameter))
                .securityContexts(Lists.newArrayList(securityContext()))
                .securitySchemes(Lists.newArrayList(apiKey()));
    }
    
    private ApiInfo simpleApiInfo() {
        return new ApiInfoBuilder().title("Swagger3接口文档").version("1.0").build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .description("Swagger3接口文档")
                .termsOfServiceUrl("https://springfox.io")
                .contact(new Contact("Swagger", "https://swagger.io", "swagger@hs.com"))
                .license("Apache License Version 2.0")
                .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE")
                .version("1.0")
                .build();
    }
    
    
    
    /**
     * new config
     * @return
     */
    private ApiKey apiKey() {
        // ApiKey的name需与SecurityReference(下面的defaultAuth方法最后一行)的reference保持一致
        return new ApiKey("token" , "token", "header");
    }
    
    private SecurityScheme securityScheme() {
        return new HttpAuthenticationBuilder().name("basic").scheme("basic").build();
    }
    
    /**
     * new config
     * @return
     */
    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                //.forPaths(PathSelectors.any())
                //.forPaths(PathSelectors.regex(DEFAULT_INCLUDE_PATTERN))
                //.forPaths(PathSelectors.regex("^(?!auth).*$"))
                .build();
    }
    
    /**
     * new config
     * @return
     */
    List<SecurityReference> defaultAuth() {
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        authorizationScopes[0] = authorizationScope;
        return Lists.newArrayList(new SecurityReference("token", authorizationScopes));
    }

}
